package com.zw.pm.module.system.login;

import com.zw.pm.annotation.LogAnnotation;
import com.zw.pm.base.BaseController;
import com.zw.pm.common.JsonResult;
import com.zw.pm.gen.entity.User;
import com.zw.pm.module.system.user.UserService;
import com.zw.pm.util.ServletUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description: 登录控制器
 *
 * @Author: China.sgl
 * @Date: 2019/9/19 09:41
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private UserService userService;

    @Value("${spring.profiles.active}")
    private String profile;
    /**
     * 登录页面
     *
     * @return 页面路径
     */
    @GetMapping("/")
    public String root(HttpServletRequest request, HttpServletResponse response, Model model) {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"type\":\"ERROR\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        model.addAttribute("profile", profile);
        return "/login";
    }

    /**
     * 登录
     *
     * @param user 用户
     * @return json
     */
    @ResponseBody
    @PostMapping("/login")
    @LogAnnotation(value = "登录")
    public JsonResult login(User user) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getAccount(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
            // 保存当前登录用户到 session
            User currentUser = userService.findByAccount(user.getAccount());
            Session session = subject.getSession();
            session.setAttribute("user", currentUser);
            return success();
        } catch(Exception e) {
            return error("帐号密码错误");
        }
    }


}
